package com.authine.cloudpivot.web.api.secondopen.service.impl;

import com.authine.cloudpivot.web.api.secondopen.dao.FileMapper;
import com.authine.cloudpivot.web.api.secondopen.domain.FileInfo;
import com.authine.cloudpivot.web.api.secondopen.service.FileUpLoadService;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;

@Service
public class FileUpLoadServiceImpl implements FileUpLoadService {
    private static final Logger log = LoggerFactory.getLogger(FileUpLoadServiceImpl.class);

    @Autowired
    private FileMapper fileMapper;

    @Override
    public Boolean upFile(List<FileInfo>  files,String khmc) {
        String url="smb://192.9.200.206/包装基准书-bpm审批版/包装基准书/";
        Boolean flag=false;
        for (int i = 0; i < files.size(); i++) {
            FileInfo fileInfo = files.get(i);
            String filename = fileInfo.getFilename();
            String mimetyep = fileInfo.getMimetyep();
            String refid = fileInfo.getRefid();
            Integer size = fileInfo.getSize();

            HttpGet httpGet = new HttpGet("http://192.9.200.117:5600/api/api/aliyun/download"+"?refId="+refid);
//            httpGet.setProtocolVersion(HttpVersion.HTTP_1_0);
            InputStream in = null;
            OutputStream out=null;
            BufferedInputStream br=null;
            try(CloseableHttpClient httpClient= HttpClients.createDefault()) {
                RequestConfig timeoutconfig = RequestConfig.custom().setConnectTimeout(5000).
                        setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
                httpGet.setConfig(timeoutconfig);
                HttpResponse response = httpClient.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statuscode = statusLine.getStatusCode();
                if (statuscode == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    in = httpEntity.getContent();
                }
                try {
                    //设置用户名密码
                    NtlmPasswordAuthentication auth=new NtlmPasswordAuthentication(null,"ATG\\bzjzsoa","test*168");
                    //遍历文件夹
                    SmbFile openFile = new SmbFile(url,auth);
                    String dirName=null;
                    String[] dirList = openFile.list();
                    for (String s: dirList) {
                        if (s.contains(khmc)){
                            dirName=s;
                        }
                    }
                    //封装连接对象
                    SmbFile remoteFile = new SmbFile(url+dirName+"/"+filename,auth);
                    //与服务器建立连接
                    remoteFile.connect();
                    br =new BufferedInputStream(in);
                    out= new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
                    log.info("开始上传");
                    int len =0;
                    byte[] ch=new byte[1024];
                    while ((len=br.read(ch))!= -1){
                        out.write(ch,0,len);
                        //ch =new byte[4096];
                    }
                    flag=true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }catch (Exception e) {
                log.info("获取文件失败");
                e.printStackTrace();
            }
             finally {
                try{
                    in.close();
                    br.close();
                    out.close();
                }catch (IOException e){
                    log.info("关闭文件流失败");
                    e.printStackTrace();
                }
            }
        }
            return flag;
    }

    @Override
    public List<FileInfo> getFileById(String id) {
        List<FileInfo> fileById = fileMapper.getFileById(id);
        return fileById;
    }

    @Override
    public void copyFile(String khmc, String fileName) {
        try {
            //设置用户名密码
            NtlmPasswordAuthentication auth=new NtlmPasswordAuthentication(null,"ATG\\bzjzsoa","test*168");
            String url="smb://192.9.200.206/包装基准书-bpm审批版/包装基准书/";
            String oldurl="smb://192.9.200.206/包装基准书-bpm审批版/包装基准书老版本/";
            //封装连接对象
            SmbFile remoteFile = new SmbFile(url,auth);
            //与服务器建立连接
            remoteFile.connect();
            //遍历文件夹
            String dirName="比亚迪汽车有限公司";
            String[] dirList = remoteFile.list();
            for (String s: dirList) {
                if (s.contains(khmc)){
                    dirName=s;
                }
            }
            //连接到文件夹
            SmbFile remoteFile1= new SmbFile(url+dirName+"/", auth);
            String[] newList = remoteFile1.list();
            //需要操作的文件
            String findFileName=null;
            for (String s:newList) {
                if (s.contains(fileName)){
                    findFileName=s;
                }
            }
            if (StringUtils.isEmpty(findFileName)){
                return;//未找到文件
            }
            //连接到新文件
            SmbFile newFile= new SmbFile(url+dirName+"/"+findFileName, auth);

            //连接到旧文件
            SmbFile oldFile = new SmbFile(oldurl+dirName+"/"+findFileName, auth);
            //移动文件
            newFile.copyTo(oldFile);
            //删除文件
            newFile.delete();

            //上传文件
            System.out.println(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
